#!/bin/bash

# 定义颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # 无颜色

# 检查是否有root权限
if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}请使用root权限运行此脚本${NC}"
  exit 1
fi

BASEDIR=/opt/mysql
DATADIR=/opt/mysql/data

# 停止MySQL服务
echo -e "${YELLOW}停止MySQL服务...${NC}"
systemctl stop mysqld
if [ $? -ne 0 ]; then
  echo -e "${RED}停止MySQL服务失败${NC}"
  exit 1
fi

# 禁用MySQL服务
echo -e "${YELLOW}禁用MySQL服务...${NC}"
systemctl disable mysqld
if [ $? -ne 0 ]; then
  echo -e "${RED}禁用MySQL服务失败${NC}"
  exit 1
fi

# 移除mysqld服务文件
echo -e "${YELLOW}移除mysqld服务文件...${NC}"
rm /usr/lib/systemd/system/mysqld.service
if [ $? -ne 0 ]; then
  echo -e "${RED}移除mysqld服务文件失败${NC}"
  exit 1
fi

# 重新加载systemd守护进程
echo -e "${YELLOW}重新加载systemd守护进程...${NC}"
systemctl daemon-reload
if [ $? -ne 0 ]; then
  echo -e "${RED}重新加载systemd守护进程失败${NC}"
  exit 1
fi

# 删除MySQL用户和组
echo -e "${YELLOW}删除MySQL用户和组...${NC}"
userdel mysql
if [ $? -ne 0 ]; then
  echo -e "${RED}删除MySQL用户失败${NC}"
  exit 1
fi

# 删除MySQL目录
echo -e "${YELLOW}删除MySQL目录...${NC}"
rm -rf "$BASEDIR"
if [ $? -ne 0 ]; then
  echo -e "${RED}删除MySQL目录失败${NC}"
  exit 1
fi
rm -rf "$DATADIR"
if [ $? -ne 0 ]; then
  echo -e "${RED}删除MySQL数据目录失败${NC}"
  exit 1
fi

# 删除环境变量
echo -e "${YELLOW}删除环境变量...${NC}"
sed -i '\|export PATH=\$PATH:'"${BASEDIR}/bin"'|d' /etc/profile
if [ $? -ne 0 ]; then
  echo -e "${RED}删除环境变量失败${NC}"
  exit 1
fi

# 删除MySQL相关的日志文件
echo -e "${YELLOW}删除MySQL相关的日志文件...${NC}"
rm -rf /var/log/mysql
if [ $? -ne 0 ]; then
  echo -e "${RED}删除MySQL相关的日志文件失败${NC}"
  exit 1
fi

# 提示用户MySQL已卸载
echo -e "${GREEN}MySQL已成功卸载并清理${NC}"
